package com.example.service.impl;

import com.example.entity.Ebook;
import com.example.entity.EbookExample;
import com.example.mapper.EbookMapper;
import com.example.req.EbookQueryReq;
import com.example.req.EbookSaveReq;
import com.example.service.EbookService;
import com.example.utils.CopyUtil;
import com.example.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class EbookServiceImpl implements EbookService {

    @Autowired
    EbookMapper ebookMapper;

    @Autowired
    SnowFlake snowFlake;

    @Override
    public PageInfo<Ebook> findEbook(EbookQueryReq req) {

        System.out.println(req.getId());
        System.out.println(req.getName());
        System.out.println("当前页"+req.getPageNum());
        System.out.println(req.getPageSize());

        EbookExample example = new EbookExample();

        EbookExample.Criteria criteria = example.createCriteria();

        if(!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%"+req.getName()+"%");
        }
        if(!ObjectUtils.isEmpty(req.getCategory2Id())){
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }

        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(example);
        System.out.println(ebookList.size());
        PageInfo<Ebook> ebookPageInfo = new PageInfo<>(ebookList);
        return ebookPageInfo;
    }

    @Override
    public void saveEbook(EbookSaveReq req) {

        Ebook ebook = CopyUtil.copy(req, Ebook.class);

        if(ObjectUtils.isEmpty(ebook.getId())){

            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);

        }else{
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    @Override
    public void deleteEbook(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
